package com.example.demo.service.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;


@Slf4j
@Component
public class ChatMessageRedisListener implements MessageListener {

    private final RedisTemplate redisTemplate;

    private static final int QUEUE_SIZE = 5000;

    private static ArrayBlockingQueue<String> messageQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);

    public ChatMessageRedisListener(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = (String) redisTemplate.getStringSerializer().deserialize(message.getChannel());
        String messageStr = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        log.info("redis message listener ======> channel:{}, message:{}", channel, messageStr);
        try {
            messageQueue.put(messageStr);
        } catch (InterruptedException e) {
            log.error("消息加入队列异常", e);
        }
    }

    /**
     * 队列消费，此处使用单独线程处理队列消息
     *
     */
    public void consumeMessageQueue() {
        while (true) {
            try {
                String message = messageQueue.take();
                //发送消息，测试用，直接打印
                log.info("redis message listener ======> message:{}", message);
            } catch (InterruptedException e) {
                log.error("消息队列消费异常", e);
            }
        }
    }
}
